<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    :width="width"
    @close="reset"
  >
    <el-form label-position="top" ref="formRef" :model="form" :rules="rules">
      <el-form-item :label="$t('component.bizSendEmail.label.recipient')">
        <el-radio-group v-model="form.linkManType" :disabled="pending">
          <el-radio label="0" :style="{ width: '120px' }">
            {{$t('component.bizSendMessage.contactRadio[0]')}}
          </el-radio>
          <el-radio label="1" :style="{ width: '120px' }">
            {{$t('component.bizSendMessage.contactRadio[1]')}}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="$t('component.bizSendEmail.label.subject')" prop="subject">
        <el-input v-model="form.subject" maxlength="200"></el-input>
      </el-form-item>
      <el-form-item :label="$t('component.bizSendEmail.label.content')" prop="emailTemplateContent">
        <el-input
          type="textarea"
          v-model="form.emailTemplateContent"
          rows="5"
          resize="none"
        ></el-input>
      </el-form-item>
      <el-form-item :label="$t('component.bizSendEmail.label.sendTime')" prop="sendTime" :error="error">
        <div class="flex-x">
          <el-radio v-model="form.sendTimeType" :label="1" @change="sendTimeTypeChange">{{ $t('common.base.immediately') }}</el-radio>
          <el-radio class="mar-l-24" v-model="form.sendTimeType" :label="2" @change="sendTimeTypeChange">{{ $t('common.base.atRegularTime') }}</el-radio>
          <el-date-picker
            class="mar-l-12"
            popper-class="message-date-picker"
            v-show="form.sendTimeType === 2"
            v-model="form.sendTime"
            type="datetime"
            :placeholder="$t('common.placeholder.selectDateTime')"
            :picker-options="datePickerOption"
            default-time="12:00"
            format="yyyy-MM-dd HH:mm"
            value-format="timestamp"
          >
          </el-date-picker>
        </div>
      </el-form-item>
    </el-form>

    <div slot="footer">
      <el-button @click="dialogVisible = false">{{$t('common.base.cancel')}}</el-button>
      <el-button type="primary" @click="onSubmit" :disabled="pending">
        {{$t('common.base.confirm')}}
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import * as CustomerApi from '@src/api/CustomerApi.ts';
import i18n from '@src/locales';
import moment from 'moment'

export default {
  name: 'biz-send-email',
  data: () => {
    const validateTime = (rule, value, callback) => {
      if(!value) {
        callback(new Error(i18n.t('common.validate.requiredSendTime')));
      } else if(value < +new Date()) {
        callback(new Error(i18n.t('common.validate.invalidSendTime')));
      } else {
        callback();
      }
    };
    return {
      form: {},
      rules: {
        subject: { required: true, message: i18n.t('common.validate.requiredSubjectContent'), trigger: ['blur'] },
        emailTemplateContent: { required: true, message: i18n.t('common.validate.requiredEmailContent'), trigger: ['blur'] },
      },
      dialogVisible: false,
      pending: false,
      datePickerOption: {
        disabledDate(time) {
          return time.getTime() < Date.now();
        },
      },
      error: '',
    };
  },
  props: {
    mode: {
      type: String,
      default: 'CUSTOMER',
    },
    title: {
      type: String,
      default: i18n.t('common.base.sendEmail'),
    },
    width: {
      type: String,
      default: '600px',
    },
    selectedIds: {
      type: Array,
      default: () => [],
    },
  },
  created() {
    this.reset()
  },
  methods: {
    sendTimeTypeChange() {
      this.error = '';
    },
    async onSubmit() {
      const { sendTime, sendTimeType } = this.form;
      this.error = '';

      if (sendTimeType == 2) {
        if (!sendTime) {
          return this.error = i18n.t('common.validate.requiredSendTime');
        } else if(sendTime < +new Date()) {
          return this.error = i18n.t('common.validate.invalidSendTime');
        }
      }

      this.$refs.formRef.validate(async valid => {
        if(!valid) return false;
        const payload = {
          ...this.form,
          personType: this.mode,
          primaryIds: this.selectedIds,
        }

        // 选择立即时，发送时间为当前时间(这里后端加了校验，增加5秒)
        if (sendTimeType == 1) {
          payload.sendTime = moment(+new Date()).add(5, 'seconds').valueOf();
        }

        this.pending = true;
        const { success, message } = await CustomerApi.sendEmail(payload);

        this.pending = false;
        if(success) {
          this.$platform.notification({
            title: i18n.t('common.base.tip.batchSendEmailSuccess'),
            type: 'success',
          });
          this.dialogVisible = false;
        } else {
          this.$message.error(message);
        }
      })
    },

    openDialog() {
      if (!this.selectedIds.length) {
        return this.$platform.alert(i18n.t('common.base.tip.selectSendEmailCustomer'));
      }
      this.$refs.formRef?.clearValidate?.();
      this.dialogVisible = true;
    },

    reset() {
      this.$set(this, 'form', {
        linkManType: '0',
        subject: '',
        emailTemplateContent: i18n.t('component.bizSendEmail.emailTemplateContent'),
        sendTime: moment(+new Date()).valueOf(),
        sendTimeType: 1,
      })
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__body {
  padding: 30px 20px;
  border-bottom: 0;
  .el-form {
    .flex-x {
      .el-radio {
        line-height: 32px;
        margin-right: 0;
        &.mar-l-24 {
          margin-left: 24px;
        }
      }
    }
  }
}
.message-date-picker {
  .el-picker-panel__footer .el-button--text.el-picker-panel__link-btn {
    display: none;
  }
}
</style>
